package com.gitee.wsl.collections.iterator

import com.gitee.wsl.func.Function

class SelectNextIterator<T>(
    val provider: Function<T?, List<T>>
) : Iterator<T> {

    private var entityList = emptyList<T>()
    private var currentIndex = 0
    private var lastEntity: T? = null
    private var eof = false

    override fun hasNext(): Boolean {
        if (eof) return false

        if (!entityList.isEmpty()) {
            return true
        }

        return fetchNext()
    }

    private fun fetchNext(): Boolean {
        currentIndex = 0
        entityList = provider(lastEntity)
        if (entityList.isEmpty()) {
            eof = true
            return false
        }
        lastEntity = entityList[entityList.size - 1]
        return true
    }

    override fun next(): T {
        if (!hasNext()) throw NoSuchElementException()

        val ret = entityList[currentIndex++]
        if (currentIndex >= entityList.size) entityList = emptyList<T>()
        return ret
    }
}